package com.fleafinder;

import java.util.List;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.fleafinder.entity.MarketType;

public class GridViewButtonAdapter extends BaseAdapter implements
		OnClickListener {

	private Context context;
	private List<MarketType> marketTypeList = null;

	public GridViewButtonAdapter(Context context) {
		this.context = context;

		try {
			// TODO: [fleafinder] this should not use flag
			// "isLoadingMarketList", but flag "isLoadingMarketTypeList"
			while (DataCenter.getInstance().isLoadingMarketList() == true) {
				Thread.sleep(CommonConstants.DEFAULT_SLEEP_TIME);
			}
			marketTypeList = DataCenter.getInstance().getMarketTypeList();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public int getCount() {
		return this.marketTypeList.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService((Context.LAYOUT_INFLATER_SERVICE));

		View buttonView = null;

		if (this.marketTypeList != null) {
			if (convertView == null) {
				buttonView = inflater
						.inflate(R.layout.grid_button_layout, null);

				final ImageView btnImageView = (ImageView) buttonView
						.findViewById(R.id.grid_button_image);
				btnImageView.setOnClickListener(this);
				btnImageView.setTag(this.marketTypeList.get(position)
						.getMarketId());

				final TextView btnTextView = (TextView) buttonView
						.findViewById(R.id.grid_button_text);
				btnTextView.setTag(this.marketTypeList.get(position)
						.getMarketId());
				btnTextView.setText(this.marketTypeList.get(position)
						.getMarketTypeName());
				btnTextView.setOnClickListener(this);
			} else {
				buttonView = convertView;
			}
		}

		return buttonView;
	}

	@Override
	public void onClick(View v) {
		String tag = CommonConstants.HOME_FRAGMENT;
		DataCenter dc = DataCenter.getInstance();
		dc.setRootFragmentOfTab(false);
		Integer marketTypeId = (Integer) v.getTag();
		dc.setSelectedmarketTypeId(marketTypeId);

		FragmentActivity activity = (FragmentActivity) v.getContext();
		FragmentManager fm = activity.getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();

		transaction.replace(R.id.fragment_placeholder,
				dc.getCategoryListFragment(), tag);

		dc.getCategoryListFragment().updateMarketTypeTitle();

		transaction.addToBackStack(tag);
		transaction.commit();
	}
}